//
//  ChallengeModelViewController.m
//  LittleFairyPoet
//
//  Created by rimi on 15/9/11.
//  Copyright (c) 2015年 周林. All rights reserved.
//

#import "WPReciteModelViewController.h"
#import "WKAlertView.h"
#import "WPAlerView.h"

typedef NS_ENUM(NSInteger, buttonTag) {
    buttonItemTag = 100,
};
@interface WPReciteModelViewController ()
{
    NSMutableArray *_poemSource;/**< 截取后的字库 */
    NSMutableArray *_wordSource;/**< 截取出来的字库 */
    NSInteger _wordAmount;//被隐藏作为题目的那句诗的字数
}
@property (nonatomic, strong) NSMutableArray * dataSource;
@property (nonatomic, strong) UIButton *backButton; /**< 返回 */
@property (nonatomic, strong) UILabel *poemTitle; /**< 诗名 */
@property (nonatomic, strong) UILabel *poetName; /**< 诗人 */
@property (nonatomic, strong) UILabel *poemContent; /**< 诗正文 */
@property (nonatomic, strong) UIButton *lastButton; /**< 上一题 */
@property (nonatomic, strong) UIButton *nextButton; /**< 下一题 */
@property (nonatomic, strong) UIImageView *backgroundImage; /**< 背景图 */


@property (nonatomic, strong) NSMutableArray * btnArray;/**< 字按键数组方便移除 */
@property (nonatomic, copy) NSMutableString * answerStr;
@property (nonatomic, strong) NSMutableArray * answerResult;/**< 结果数组 */
@property (nonatomic, assign) NSUInteger answerIndex;/**< 答案下标 */
@property (nonatomic, strong) UIWindow *topdWindow;/**< 提示窗口 */



- (void)initializeDataSource; /**< 初始化数据源 */
- (void)initializeUserInterface; /**< 初始化用户界面 */
- (void)createButtonArrayCount20;
- (void)createButtonArrayCount28;

@end

@implementation WPReciteModelViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initializeDataSource];
    [self initializeUserInterface];
}
#pragma mark - private methods 
- (void)initializeDataSource {
    if (_poemArray.count == 0) {
       
        //获取plist的bundle路径
        NSString *plistPath = [[NSBundle mainBundle] pathForAuxiliaryExecutable:@"绝句.plist"];
        _dataSource = [NSMutableArray array];
        NSMutableArray *arr1 = [NSMutableArray arrayWithArray:[NSArray arrayWithContentsOfFile:plistPath]];
        NSMutableArray *arr2 = [NSMutableArray arrayWithArray:[self randomFromNumber:0 toNumber:arr1.count-1]];
        
        for (int i = 0; i < arr1.count; i++) {
            [self.dataSource addObject:arr1[[arr2[i] integerValue]]];
        }
        _count = arc4random() % _dataSource.count;
    } else {
        self.dataSource = [NSMutableArray arrayWithArray:_poemArray];
    }
    _answerIndex = 0;
}
- (void)initializeUserInterface {
    self.view.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.backgroundImage];
    [self.view addSubview:self.poemTitle];
    [self.view addSubview:self.backButton];
    [self.view addSubview:self.poetName];
    [self.view addSubview:self.poemContent];
    [self.view addSubview:self.lastButton];
    [self.view addSubview:self.nextButton];
    if (self.poemDict.count > 0) {
        _poemTitle.text = _poemDict[@"title"];
        _poetName.text = _poemDict[@"zuozhe"];
    }
    [self poemSegementation];
    [self makeWordInWordSource];
}

#pragma mark - action
- (void)action_gameButton:(UIButton *)sender {
    if (_answerIndex >= 4) {
        return;
    }
    sender.hidden = YES;
    [self.answerStr insertString:sender.titleLabel.text atIndex:(_answerStr.length)];
    NSMutableString * poem = [self.poemContent.text mutableCopy];
    [poem replaceCharactersInRange:NSMakeRange((_wordAmount+2)*_answerIndex,_answerStr.length) withString:_answerStr];
    NSMutableAttributedString * poemDetail = [[NSMutableAttributedString alloc]initWithString:poem];
    self.poemContent.attributedText = poemDetail;
    if (self.answerStr.length == _wordAmount) {
        [self.answerResult addObject:_answerStr];
        if (![_answerStr isEqualToString:_poemSource[_answerIndex]]) {
            NSMutableAttributedString * attriString = [[NSMutableAttributedString alloc]initWithString:self.poemContent.text];
            [attriString addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange((_wordAmount+2)*_answerIndex,_wordAmount)];
            self.poemContent.attributedText = attriString;
            _answerIndex = 4;
            
            self.topdWindow = [WKAlertView showAlertViewWithStyle:WKAlertViewStyleFail title:@"很遗憾" detail:@"差一点就答对啦，加油哦!" canleButtonTitle:nil okButtonTitle:@"确定" callBlock:^(MyWindowClick buttonIndex) {
                _answerIndex = 0;
                _topdWindow.hidden = YES;
                _topdWindow = nil;
                [self makeWordInWordSource];
                }];
        }
        _answerStr = nil;
        ++_answerIndex;
    }
    if (_answerIndex == 4) {
        self.topdWindow = [WKAlertView showAlertViewWithStyle:WKAlertViewStyleSuccess title:@"恭喜你" detail:@"完全回答正确,真厉害!" canleButtonTitle:nil okButtonTitle:@"下一关" callBlock:^(MyWindowClick buttonIndex) {
            [self action_nextButton];
            _topdWindow.hidden = YES;
            _topdWindow = nil;
        }];
    }
}

- (void)action_hormButton:(UIButton *)sender {
    sender.selected = !sender.selected;
}

- (void)action_backButton:(UIButton *)sender {
    
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)action_lastButton:(UIButton *)sender {
    if (_count == 0) {
        [WPAlerView showAlertViewWithMsg:@"已经是第一首了"];
        return;
    }
    self.answerStr = nil;
    _count--;
    _poemTitle.text = _dataSource[_count][@"title"];
    _poetName.text = [NSString stringWithFormat:@"%@·%@", _dataSource[_count][@"zuozhe"], _dataSource[_count][@"chaodai"]];
    _poemContent.text = _dataSource[_count][@"content"];
    [self poemSegementation];
    [self makeWordInWordSource];
}

- (void)action_nextButton {
    if (_count == _dataSource.count-1) {
        [WPAlerView showAlertViewWithMsg:@"已经是最后一首了"];
        return;
    }
    self.answerStr = nil;
    _count++;
    _poemTitle.text = _dataSource[_count][@"title"];
    _poetName.text = [NSString stringWithFormat:@"%@·%@", _dataSource[_count][@"zuozhe"], _dataSource[_count][@"chaodai"]];;
    _poemContent.text = _dataSource[_count][@"content"];
    [self poemSegementation];
    [self makeWordInWordSource];
}
#pragma mark - private method
//循环创建button
- (void)createButtonArrayCount20 {
    if (self.btnArray.count > 0) {
        [self removeBtnArray];
        [_btnArray removeAllObjects];
    }
    for (int i = 0; i < 20; i++) {
        NSInteger line = i / 5;
        NSInteger row = i % 5;
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = DHFlexibleFrame(CGRectMake(10 + row * 60, 280 + line * 60, 50, 50), YES);
        button.backgroundColor = ZLColor(252, 186, 44);
        button.tag = buttonItemTag + i;
        button.layer.cornerRadius = 5;
        [_btnArray addObject:button];
        [self.view addSubview:button];
        [button addTarget:self action:@selector(action_gameButton:) forControlEvents:UIControlEventTouchUpInside];
    }
    //随机选出几个button填上字
    [self fillWordInButton];
}
- (void)createButtonArrayCount28 {
    if (self.btnArray.count > 0) {
        [self removeBtnArray];
    }
    for (int i = 0; i < 28; i++) {
        NSInteger line = i / 7;
        NSInteger row = i % 7;
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = DHFlexibleFrame(CGRectMake(10 + row * 43, 280 + line * 60, 33, 50), YES);
        button.backgroundColor = ZLColor(252, 186, 44);
        button.tag = buttonItemTag + i;
        button.layer.cornerRadius = 5;
        [self.view addSubview:button];
        
        [_btnArray addObject:button];
        [button addTarget:self action:@selector(action_gameButton:) forControlEvents:UIControlEventTouchUpInside];
    }
    //随机选出几个button填上字
    [self fillWordInButton];
}
- (void)removeBtnArray {
    if (self.btnArray.count == 0) {
        return;
    }
    for (UIButton * btn in self.btnArray) {
        [btn removeFromSuperview];
    }
}

//将plist中的诗乱序且不重复
- (NSMutableArray *)randomFromNumber:(NSInteger)fromNumber toNumber:(NSInteger)toNumber {
    NSMutableArray *arr1 = [NSMutableArray array];
    for (NSInteger i = fromNumber; i <= toNumber; i++) {
        [arr1 addObject:@(i)];
    }
    for (int i = 0; i <= 100; i++) {
        NSInteger value = arc4random() % (toNumber - fromNumber + 1);
        [arr1 exchangeObjectAtIndex:value withObjectAtIndex:0];
    }
    return arr1;
}

//将一首诗分成4句装入数组中
- (void)poemSegementation {
    _poemSource = [NSMutableArray array];
    NSMutableString * string = nil;
    string = [_dataSource[_count][@"content"] mutableCopy];
    NSString *temp = nil;
    int j = 0;
    for (int i = 0; i < string.length; i++) {
        for (j = i; j < string.length; j++) {
            temp = [string substringWithRange:NSMakeRange(j, 1)];
            if ([temp isEqualToString:@"，"] || [temp isEqualToString:@"？"] || [temp isEqualToString:@"。"] || [temp isEqualToString:@"；"] || [temp isEqualToString:@"！"]) {
                [_poemSource addObject:[string substringWithRange:NSMakeRange(i, j - i)]];
                j = j + 2;
                i = j;
            }
        }
    }
}
//将随机取出的一句诗的文字挨个截取出来装入一个数组中
- (void)makeWordInWordSource {
    _wordSource = [NSMutableArray new];
    for (int i = 0; i < 4; i++) {
        NSInteger j = ((NSString *)_poemSource[i]).length;//这句诗有多少个字
        _wordAmount = j;
        NSString * string = _poemSource[i];
        for (int k = 0; k < j; k ++) {
            NSString * word = [string substringWithRange:NSMakeRange(k, 1)];
            [_wordSource addObject:word];
        }
        NSString * sentence = (NSString *)_poemSource[i];
        NSString * line = @"－" ;
        for (int k = 0; k <= sentence.length - 2 ; k++) {
            line = [line stringByAppendingString:@"－"];
        }
        NSMutableString * poem = [self.poemContent.text mutableCopy];
        [poem replaceCharactersInRange:NSMakeRange(i*(_wordAmount + 2), _wordAmount) withString:line];
        NSMutableAttributedString * poemAtt = [[NSMutableAttributedString alloc]initWithString:poem];
        _poemContent.attributedText = poemAtt;
    }
    if (_wordSource.count < 24) {
        [self createButtonArrayCount20];
    } else {
        [self createButtonArrayCount28];
    }
    
}

//随机选出几个button填上字
- (void)fillWordInButton {
    NSMutableArray *array = [self randomFromNumber:100 toNumber:_wordSource.count-1+100];
    for (int j = 0; j < _wordSource.count; j++) {
        NSInteger button_tag = [array[j] integerValue];
        UIButton * button = (UIButton *)[self.view viewWithTag:button_tag];
        [button setTitle:_wordSource[j] forState:UIControlStateNormal];
        [button setTitleColor:ZLColor(119, 66, 32) forState:UIControlStateNormal];
        button.titleLabel.font = [UIFont fontWithName:@"AmericanTypewriter-Bold" size:20];
    }
}
#pragma mark - getter
- (UIButton *)backButton {
    if (!_backButton) {
        _backButton = ({
            UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
            button.frame = DHFlexibleFrame(CGRectMake(5, 15, 90, 50), YES);
            [button setImage:IMAGE_CONTENT(@"返回主菜单.png") forState:UIControlStateNormal];
            [button addTarget:self action:@selector(action_backButton:) forControlEvents:UIControlEventTouchUpInside];
            button;
        });
    }
    return _backButton;
}

- (UILabel *)poemTitle {
    if (!_poemTitle) {
        _poemTitle = ({
            UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(60, 50, 200, 60) adjustWidth:YES];
            label.textAlignment = NSTextAlignmentCenter;
            label.numberOfLines = 0;
            label.text = _dataSource[_count][@"title"];
            label.textColor = [UIColor darkGrayColor];
            label.textAlignment = NSTextAlignmentCenter;
            label.font = [UIFont fontWithName:@"Kaiti" size:22];
            label.numberOfLines = 0;
            label;
        });
    }
    return _poemTitle;
}

- (UILabel *)poetName {
    if (!_poetName) {
        _poetName = ({
            UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(180, 95, 130, 30) adjustWidth:YES];
            label.textAlignment = NSTextAlignmentLeft;
            label.text = [NSString stringWithFormat:@"%@(%@)", _dataSource[_count][@"zuozhe"], _dataSource[_count][@"chaodai"]];
            label.textColor = [UIColor darkGrayColor];
            label.numberOfLines = 0;
            label.font = [UIFont fontWithName:@"Kaiti" size:18];
            label;
        });
    }
    return _poetName;
}

- (UILabel *)poemContent {
    if (!_poemContent) {
        _poemContent = ({
            UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(50, 110, 220, 180) adjustWidth:YES];
            label.textAlignment = NSTextAlignmentCenter;
            NSMutableString *string = [_dataSource[_count][@"content"] mutableCopy];
            label.numberOfLines = 0;
            label.text = string;
            label.textColor = [UIColor darkGrayColor];
            label.font = [UIFont fontWithName:@"Kaiti" size:22];
            label;
        });
    }
    return _poemContent;
}

- (UIButton *)lastButton {
    if (!_lastButton) {
        _lastButton = ({
            UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
            button.frame = DHFlexibleFrame(CGRectMake(60, 520, 70, 30), YES);
            //button.backgroundColor = [UIColor blueColor];
            [button setImage:IMAGE_CONTENT(@"上一题.png") forState:UIControlStateNormal];
            [button addTarget:self action:@selector(action_lastButton:) forControlEvents:UIControlEventTouchUpInside];
            button;
        });
    }
    return _lastButton;
}

- (UIButton *)nextButton {
    if (!_nextButton) {
        _nextButton = ({
            UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
            button.frame = DHFlexibleFrame(CGRectMake(190, 520, 70, 30), YES);
            //button.backgroundColor = [UIColor blueColor];
            [button setImage:IMAGE_CONTENT(@"下一题.png") forState:UIControlStateNormal];
            [button addTarget:self action:@selector(action_nextButton) forControlEvents:UIControlEventTouchUpInside];
            button;
        });
    }
    return _nextButton;
}

- (UIImageView *)backgroundImage {
    if (!_backgroundImage) {
        _backgroundImage = ({
            UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, ORIGIN_WIDTH, ORIGIN_HEIGHT) adjustWidth:NO];
            imageView.image = IMAGE_CONTENT(@"背景1.jpg");
            imageView;
        });
    }
    return _backgroundImage;
}

- (BOOL)prefersStatusBarHidden {
    return YES;
}
- (NSMutableArray *)btnArray {
    if (!_btnArray) {
        _btnArray = [NSMutableArray array];
    }
    return _btnArray;
}
- (NSMutableString *)answerStr {
    if (!_answerStr) {
        _answerStr = [NSMutableString string];
    }
    return _answerStr;
}
- (NSMutableArray *)answerResult {
    if (!_answerResult) {
        _answerResult = [NSMutableArray array];
    }
    return _answerResult;
}
@end
